<template>
  <table class="jstable" border="1" cellspacing="0">
    <!-- <button @click="edit">修改第一条数据</button> -->
    <thead>
      <tr>
        <th class="w38" rowspan="2">
          <label class="ordersCheckbox">
            <input
              :checked="false"
              onclick="getAll(event.target.checked)"
              type="checkbox"
              name="hobby"
              class="all"
              id="checkall"
            />
            <span class="checkmark"></span>
          </label>
        </th>
        <th rowspan="2">Order1s</th>
        <th rowspan="2">Store</th>
        <th rowspan="2">Shipping address</th>
        <th rowspan="2">Product</th>
        <th class="j-b-l tcenter" colspan="3">ScareOrder Quote</th>
      </tr>
      <tr>
        <th class="j-b-l">Product cost</th>
        <th class="j-b-l">Shipping</th>
        <th class="j-b-l tright">Total</th>
      </tr>
    </thead>
    <tbody id="address-td"></tbody>
  </table>
  <DefaultPage v-if="!tableData.length" />

  <div v-if="tableData.length" class="pagination">
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 50, 100, 200, 500]"
      layout="total,sizes,  prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      background
    />
  </div>

  <!-- popover -->
  <transition name="fade" type="transition">
    <div
      ref="popoverRef"
      class="editPopover"
      :style="{ top: position.top + 'px', left: position.left + 'px' }"
      v-show="isVisible"
    >
      <el-row>
        <el-col :span="8" class="p13777">Address1:</el-col>
        <el-col :span="16" class="p13222">665 Saratoga Rd</el-col>
      </el-row>
      <el-row>
        <el-col :span="8" class="p13777">Recipient:</el-col>
        <el-col :span="16" class="p13222">Emily Stehlik</el-col>
      </el-row>
      <el-row>
        <el-col :span="8" class="p13777">Recipient:</el-col>
        <el-col :span="16" class="p13222">Emily Stehlik</el-col>
      </el-row>

      <el-button
        link
        type="danger"
        class="dbt"
        @click="ModifyAddressVisible = true"
        >Edit</el-button
      >
    </div>
  </transition>
  <ModifyAddress @handleClose="handleClose" :open="ModifyAddressVisible" />
  <EditMaterialFlow
    @handleClose="editMaterialFlowClose"
    :open="editMaterialFlowVisible"
  />
</template>
<script lang="ts" setup>
import $ from "jquery";
import { ref, onMounted, reactive, onUnmounted, inject, watch } from "vue";
import ModifyAddress from "@/components/ModifyAddress/index.vue";
import EditMaterialFlow from "@/components/EditMaterialFlow/index.vue";
import json from "@/mock/json.json";
import { domData, fiterArr, btDom } from "./index.js";

import DefaultPage from "@/components/DefaultPage/index.vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const $router = useRouter();

const ModifyAddressVisible = ref(false);
const editMaterialFlowVisible = ref(false);

// const emit = defineEmits(["update:activeName"]);
const isAllChecked = inject("isAllChecked");
const checkedArr = inject("checkedArr");

const handleClose = () => {
  ModifyAddressVisible.value = false;
};
const editMaterialFlowClose = () => {
  editMaterialFlowVisible.value = false;
};

const popoverRef = ref(null);

const loading = ref(false);

const isVisible = ref(false);
const addressTd = ref(null);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const position = reactive({ top: 100, left: 100 });
// 获取静态数据数据渲染测试
let tableDataArr = json.data.orders;
// let tableData = fiterArr(tableDataArr).slice(0, 500);
// let tableData = fiterArr(tableDataArr);
// const edit = () => {
//   tableData.value[0].order_name = 111111111111111;
//   console.log(tableData.value[0]);
// };
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageSize.value = val;
  initTable();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  initTable();
};

// 初始化表格数据
const initTable = async () => {
  loading.value = true;
  $("#checkall").prop("checked", false);

  let res = await fiterArr(tableDataArr); //加上异步
  // let res = [];

  // 不存在 data 没有数据 中断代码执行
  if (!res) return false;

  // 赋值总条数给 total
  total.value = res.length;

  // 分页逻辑在这里体现
  let start =
    currentPage.value > 1 ? (currentPage.value - 1) * pageSize.value : 0;
  let end = currentPage.value * pageSize.value;

  tableData.value = res.slice(start, end) as any;

  addressTd.value.innerHTML = await domData(tableData.value);
  loading.value = false;
};
watch(isAllChecked.value, (newVal) => {
  getAll(newVal.checked, newVal.isAll);
});
// 全选/取消
const getAll = (e: boolean, s = true) => {
  isAllChecked.value.checked = e;
  let check = e;
  $("#checkall").prop("checked", e);
  if (!s) return;
  if (check) {
    /*
     * prop() 方法设置或返回被选元素的属性和值。
     * 当该方法用于返回属性值时，则返回第一个匹配元素的值。
     * 当该方法用于设置属性值时，则为匹配元素集合设置一个或多个属性/值对。
     * 根据官方的建议：具有 true 和 false 两个属性的属性，如 checked, selected 或者 disabled 使用prop()，其他的使用 attr()
     * */
    $("#address-td").find(":checkbox").prop("checked", true);
    $('input[name="package"]:checked').each(function () {
      // id_array.push($(this).val()); //向数组中添加元素
    });
  } else {
    $("#address-td").find(":checkbox").prop("checked", false);
  }
  let checkboxArr = [];
  $("#address-td input:checkbox:checked").map(function (i, e) {
    checkboxArr.push($(e).val());
  });
  checkedArr.value = checkboxArr;
};

const getIds = (e) => {
  console.log(e.target.value);

  if (e.target.checked) {
    ElMessage({
      type: "success",
      message: "订单值：" + e.target.value,
    });
  }

  //点击取消
  if (e.target.checked === false) {
    $("#checkall").prop("checked", false);
    isAllChecked.value.checked = false;
    isAllChecked.value.isAll = false;
  }
  //点击选中
  else {
    let nocheckedList = $("#address-td").find(":checkbox:not(:checked)").length;
    if (nocheckedList === 0) {
      $("#checkall").prop("checked", true);
      isAllChecked.value.checked = true;
      isAllChecked.value.isAll = false;
    }
  }

  let checkboxArr = [];
  $("#address-td input:checkbox:checked").map(function (i, e) {
    checkboxArr.push($(e).val());
  });
  checkedArr.value = checkboxArr;
};

// 显示物流
const onEditBlock = (e) => {
  $(e.target).toggleClass("rotate180");
  $(e.currentTarget.nextElementSibling).toggle();
};

// 编辑address
const onEAditddress = (e) => {
  isVisible.value = true;
  $(".tb-link-ar").removeClass("rotate180");

  $(e.currentTarget).children(".tb-link-ar").addClass("rotate180");
  e.stopPropagation();

  let tabsContentHeight = $(".el-tabs__content").height();
  let positionTlHeight = $(".editPopover").height();
  let positionTl = $(e.currentTarget).offset();
  let tabsContent = $(".el-tabs__content").offset();

  //重置弹出层位置
  //计算是否需要偏移
  if (tabsContentHeight + tabsContent.top - positionTl.top < positionTlHeight) {
    console.log(231);

    position.top = positionTl.top - tabsContent.top - positionTlHeight - 55;
  } else {
    position.top = positionTl.top - tabsContent.top;
  }
  position.left = positionTl.left - tabsContent.left;

  console.log(position.top);
};
const handleClickOutside = (event) => {
  if (!popoverRef.value.contains(event.target)) {
    isVisible.value = false;
    $(".tb-link-ar").removeClass("rotate180");
  }
};

// 鼠标移入
const over = (e, id) => {
  $(e.currentTarget).find("td:last").append(btDom(id));
};
// 鼠标移出
const enter = () => {
  $(".jstable-tb").remove();
};
// 详情页跳转
const onDetailsPage = (e) => {
  $router.push({
    path: "/Order/ScaleOrder/OrderDetails",
    query: { value: e, type: "list" },
  });
};

// 支付跳转
const onOrder = (e) => {
  $router.push({ path: "/Order/ScaleOrder/PlaceAnOrder", query: { value: e } });
};
//
const onRemove = (e) => {
  // emit("update:activeName", 1);
  console.log($(e.currentTarget).parents("tr"));
  $(e.currentTarget).parents("tr").remove();
};

// copy
const onCopy = (event, e) => {
  console.log(event);
  event.stopPropagation();
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(e).select();
  document.execCommand("copy");
  $temp.remove();
  ElMessage({
    message: "复制成功",
    type: "success",
  });
};
const onEditMaterialFlow = (e) => {
  console.log(e);
  editMaterialFlowVisible.value = true;
};
onMounted(() => {
  initTable();
  addressTd.value = $("#address-td")[0];

  window.getAll = getAll;
  window.getIds = getIds;
  window.onEditBlock = onEditBlock;
  window.onEAditddress = onEAditddress;
  window.onDetailsPage = onDetailsPage;
  window.over = over;
  window.enter = enter;
  window.onRemove = onRemove;
  window.onOrder = onOrder;
  window.onCopy = onCopy;
  window.onEditMaterialFlow = onEditMaterialFlow;

  document.body.addEventListener("click", handleClickOutside);
});

//移除监听 组件实例被卸载后调用
onUnmounted(() => {
  // console.log('onUnmounted');
  document.body.removeEventListener("click", handleClickOutside, false);
  // window.getAll = null;
  // window.getIds = null;
  // window.onEditBlock = null;
  // window.onEAditddress = null;
  // window.onDetailsPage = null;
  // window.over = null;
  // window.enter = null;
  // window.onRemove = null;
});
</script>
<style lang="scss" scoped></style>
